import axios from 'axios'
import qs from 'qs'
import store from '../store/index'
import {Message} from 'element-ui'
import router from '../router/index'
import common from "./common";

const localhost = window.global.webSocketURL
let ajaxServe = window.location.origin+'/'
const webSocket_url = "ws://"+localhost+"/ws/"
// axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/json'
// axios.defaults.headers.common['token'] = token;
axios.defaults.baseURL = ajaxServe

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (store.state.user.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.token = store.state.user.token
  }
  if (store.state.user.operatePwd) { // 控制添加密码验证
    config.headers.password = store.state.user.operatePwd
  }
  if (config.method === 'post') {
    // config.data = qs.stringify(config.data)
  }
  return config;
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (res) {
  if(res.data.CmdState!=undefined){
    return Promise.resolve(res.data)
  }else{//通讯提示
    if (isHttpSuccess(res.data)) {
      return Promise.resolve(res.data.data==undefined?res.data:res.data.data)
    }
  }
}, function (error) {
  let status = error.response.status
  store.commit('comm/SET_STATUS', status)
  if (status == '401') {
    sessionStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
    router.push('/login')
  } else if (status == '403') {
    store.commit('user/SET_BTN_STATE', false)
    Message({showClose: true, message: error.response.data, type: 'error'})
  } else if (status == '402') {
    Message({showClose: true, message: error.response.data, type: 'error'})
  }
  return Promise.reject(error);
});


export default {
  ajaxServe,
  webSocket_url,
  localhost,
  fetch(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, params)
        .then(response => {
          if (response != undefined) resolve(response)
        }, err => {
          // console.log(err)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  fetchSimple(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(
        url,
        qs.stringify(params), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      )
        .then(response => {
          // if (response != undefined) resolve(response)
          resolve(response != undefined ? response : '')
        }, err => {
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  get(url, params) {
    if (!params) {
      params = {}
    }
    return new Promise((resolve, reject) => {
      axios.get(url, {params: params})
        .then(response => {
          resolve(response);
        }, err => {
          reject(err);
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  fetchFile(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(params),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}, responseType: 'arraybuffer'})
        .then(response => {
          resolve(response != undefined ? response : '')
        }, err => {
          // console.log(err)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  httpFormData(url, params) {
    //'multipart/form-data' application/json
    let config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
    return new Promise((resolve, reject) => {
      axios.post(url, params, config)
        .then(response => {
          resolve(response);
        }, err => {
          reject(err);
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  formatDate:common.formatDate
}

let isHttpSuccess=function(r) {
  const errorCode={1:'未登录',2:'用户不存在',3:'密码不正确',4:'验证码不正确',5:'验证码不准确',6:'无权限',
    7:'设备已存在',8:'用户禁用',9:'session丢失',10:'读取系统参数失败',11:'超时',12:"解析JSON出错",13:'参数不正确',
    14:'设备不在线',15:'命令请求不支持',16:'解析应答帧出问题',17:'应答否认',18:'文件校验错误',19:'设备不存在',20:'设备地址格式错误',
    21:'数据超范围',31:'nb deviceId不存在',32:'nb deviceId不存在'
  }
  var state=r.err?-1:0;
  if (r.CmdState != undefined) {
    state = r.CmdState
  } else {
    state = r.state||state
  }
  if (state == 0) {
    return true
  } else if (state == -1) {
    Message({showClose: true, message: (r.err || '系统错误！'), type: 'error'})
    return false
  } else if (state == 1) {
    sessionStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
    router.push('/login')
    Message({showClose: true, message: '系统未登录！', type: 'error'})
    return false
  } else {
    Message({showClose: true, message:errorCode[state]||state, type: 'error'})
    return false
  }
}
